package com.ctvit.sms.platform.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cctv.portal.sms.adapter.ws.RespBody;
import com.ctvit.framework.service.BaseService;
import com.ctvit.sms.platform.domain.MsgSendlog;
import com.ctvit.struts.common.CommonFunc;
import com.ctvit.syn.service.SyncTableInfo;
import com.ctvit.syn.service.SynchronizeDataService;

public class MsgService extends BaseService {
	private SynchronizeDataService synService;
	public void doExecSendMsg(String msgType,String reqId)throws Exception {
		String sqlString="select a.*,b.Z_MSG_CONTENT,func_get_sendchannel(a.Z_TASK_ID)as sendchanl,b.Z_MSG_TYPE, ";
		sqlString+="(select z_clientid from t_person where z_perno=Z_RECV_USR ) as clientid";//,f_receive_time_from,f_receive_time_to";
		sqlString+=" from t_msg_task as a INNER JOIN t_msg_req as b on a.Z_REQ_ID=b.Z_REQ_ID ";
//		sqlString+=" left join t_user_subs_config as c on a.Z_RECV_USR=c.f_user_id";
//		3:短信发送成功4:短信发送失败5:已阅读7:已退订,30分钟前刚创建的 或者勿扰的
		sqlString+=" where ((z_status not in ('3','4','5','7') and a.CREATE_TIMESTAMP>DATE_sub(NOW(),interval 30 MINUTE)) or z_status='6') ";
		sqlString+=" and Z_MSG_TYPE in ("+msgType+")";
		if (!StringUtils.isEmpty(reqId)){
			sqlString+=" and b.Z_REQ_ID="+reqId;
		}
		sqlString+=" ORDER BY a.Z_RECV_USR,sendchanl,a.CREATE_TIMESTAMP ";
		List<Map<String,?>> list=genericDao.executeSql(sqlString);
		if (list!=null&&list.size()>0){
			ArrayList<Map<String,?>> listUserChannl=new ArrayList<Map<String,?>>();
			String lastChanlString="",chanlString="";
			String lastUserString="",userString="",msgTypeString="",taskIdString="";
			for (Map<String,?> map : list) {
				chanlString=String.valueOf(map.get("sendchanl"));
				userString=String.valueOf(map.get("Z_RECV_USR"));
				msgTypeString=String.valueOf(map.get("Z_MSG_TYPE"));
				taskIdString=String.valueOf(map.get("Z_TASK_ID"));
				if (!listUserChannl.isEmpty()&&(!StringUtils.equals(lastUserString,userString)||!StringUtils.equals(lastChanlString,chanlString))){
					doSendMsg(listUserChannl);
					listUserChannl=new ArrayList<Map<String,?>>();
				}
				lastChanlString=chanlString;lastUserString=userString;
				if ("3".equals(msgTypeString)){//立即发送的消息任务，当为短信时，启用了立即发送时才发送
					if ("0".equals(chanlString)){
						if ("1".equals(CommonFunc.isSmsEnabled)){
							log.debug(userString+"-"+taskIdString+"短信被忽略发出");
							continue;
						}
						listUserChannl.add(map);
					}
				}else{
					listUserChannl.add(map);
				}
			}
			if (!listUserChannl.isEmpty()){
				doSendMsg(listUserChannl);
			}
		}
	}
	/**
	 * 一个用户、一个途径调用一次
	 * @param msglist
	 */
	public void doSendMsg(List<Map<String,?>> msglist)throws Exception {
		String chanlString="",userString="",contentString="",sqlString="",taskString="",clientid="";
		String fromtimeString="",totimeString="",mobile="";
		StringBuffer contentBuffer=new StringBuffer(),taskBuffer=new StringBuffer();
		for (Map<String, ?> map : msglist) {
			chanlString=String.valueOf(map.get("sendchanl"));
			clientid=String.valueOf(map.get("clientid"));
//			fromtimeString=String.valueOf(map.get("f_receive_time_from"));
//			totimeString=String.valueOf(map.get("f_receive_time_to"));
			userString=String.valueOf(map.get("Z_RECV_USR"));
			mobile=String.valueOf(map.get("Z_MOBILE"));
			taskBuffer.append(map.get("Z_TASK_ID")).append(",");
			if (StringUtils.equals(chanlString, "0")){//短信发送,将内容拼接发送
				contentBuffer.append(map.get("Z_MSG_CONTENT")).append("\n\r");
			}
		}
		taskString=taskBuffer.toString();
		taskString=taskString.substring(0, taskString.length()-1);	
		MsgSendlog msgSendlog=new MsgSendlog();
		msgSendlog.setZSendContent(contentBuffer.toString());
		msgSendlog.setZTaskIds(taskString);
		msgSendlog.setCreateTimestamp(new Timestamp(Calendar.getInstance().getTimeInMillis()));
		if (StringUtils.equals(chanlString, "0")){//短信发送
			RespBody ret=CommonFunc.batchSendSMS(mobile, contentBuffer.toString());String taskStatus="";
			if ("03".equals(ret.getCode())){
				taskStatus="3";
			}else{
				taskStatus="4";
			}
			sqlString="update t_msg_task set Z_SEND_TIME=now(),Z_STATUS='"+taskStatus+"' where Z_TASK_ID in ("+taskString+")";
			genericDao.updateBySqlStr(sqlString);
			msgSendlog.setZSendResult(ret.getCode());
			msgSendlog.setZSendType("0");
			msgSendlog.setZSmsCnt(new Long(0));//拆分条数
			if (ret!=null&&ret.getMessage()!=null)
				msgSendlog.setZSmsCnt(new Long(ret.getMessage().size()));//拆分条数
			genericDao.insert(msgSendlog);
		}else if (StringUtils.equals(chanlString, "1")){//APP推送
			String msg="您当前有"+msglist.size()+"条未阅读的消息。";
			String ret=CommonFunc.pushMsg(userString, "央视消息中心", msg, clientid),taskStatus="";
			if ("RESULT_OK".equals(ret)){
				taskStatus="1";
			}else{
				taskStatus="2";
			}
			sqlString="update t_msg_task set Z_PUSH_TIME=now(),Z_STATUS='"+taskStatus+"' where Z_TASK_ID in ("+taskString+")";
			genericDao.updateBySqlStr(sqlString);
			msgSendlog.setZSendResult(ret);
			msgSendlog.setZSendType("1");
			msgSendlog.setZSendContent(msg);
			genericDao.insert(msgSendlog);
		}else if (StringUtils.equals(chanlString, "99")){//勿扰期间的消息，现在已过勿扰时间，发送短信
			String msg="您在勿扰时间内共有"+msglist.size()+"条消息未阅读，请及时打开APP查看。";
			RespBody ret=CommonFunc.batchSendSMS(mobile, contentBuffer.toString());String taskStatus="";
			if ("03".equals(ret)){
				taskStatus="3";
			}else{
				taskStatus="4";
			}
			sqlString="update t_msg_task set Z_SEND_TIME=now(),Z_STATUS='"+taskStatus+"' where Z_TASK_ID in ("+taskString+")";
			genericDao.updateBySqlStr(sqlString);
			msgSendlog.setZSendContent(msg);
			msgSendlog.setZSendResult(ret.getCode());
			msgSendlog.setZSendType("0");
			msgSendlog.setZSmsCnt(new Long(0));//拆分条数
			if (ret!=null&&ret.getMessage()!=null)
				msgSendlog.setZSmsCnt(new Long(ret.getMessage().size()));//拆分条数
			genericDao.insert(msgSendlog);
		}else if (StringUtils.equals(chanlString, "-4")){//勿扰时间
			sqlString="update t_msg_task set Z_STATUS='6' where Z_TASK_ID in ("+taskString+")";
			genericDao.updateBySqlStr(sqlString);
		}
	}
	public void doGeneNotice(){
		genericDao.executeSql("call p_generate_msgreq('0','t_nocice');");
	}
	/**
	 * 扫描产生提醒入库，直播消息
	 */
	public void doScanMsg() {
		genericDao.executeSql("call p_generate_instock();");
		genericDao.executeSql("call p_generate_live();");
		genericDao.executeSql("call p_generate_msg_meeting();");
	}
	protected SyncTableInfo createTableInfo(String name,String[] pkFieStrings,String src,String dest,String op,String[] pkValueString){
		SyncTableInfo tableInfo = new SyncTableInfo();
		tableInfo.setTablename(name);
		tableInfo.setPkFieldName(pkFieStrings);
		tableInfo.setSourceDb(src);
		tableInfo.setDestDb(dest);
		tableInfo.setOp(op);
		tableInfo.setPkFieldValue(pkValueString);
		return tableInfo;
	}
	/**
	 * 执行存储过程，立即启动同步，执行发送
	 * @param procName
	 * @param tableNanme
	 * @param para
	 */
	public void doExecProc(String procName,String tableNanme,String para){
		List list=genericDao.executeSql("call "+procName+"('"+ para + "','"+tableNanme+"');");
		if (list!=null&&list.size()>0){
			HashMap map=(HashMap)list.get(0);
			String type=(String)map.get("msgType");
			final String[] typeStrings=type.split(",");
			final List<SyncTableInfo> syncTableInfos=new ArrayList<SyncTableInfo>();
			SyncTableInfo tableInfo=null;
			tableInfo = createTableInfo("t_msg_req",new String[]{"Z_REQ_ID"},"local","remote","insert",new String[]{typeStrings[1]});
			syncTableInfos.add(tableInfo);
			tableInfo = createTableInfo("t_msg_task",new String[]{"Z_TASK_ID"},"local","remote","insert",new String[]{typeStrings[1]});
			syncTableInfos.add(tableInfo);
			ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
			executorService.schedule(new Runnable() {  
	            @Override  
	            public void run() {  
	                try {  
	                	synService.synchronizeDataEmergent(syncTableInfos);
	                	GetMethod getMethod=null;
	        			HttpClient httpClient = null;
	        			try {
	        				getMethod=new GetMethod(CommonFunc.remoteFileRecvUrl+"?action=exec&reqId="+typeStrings[1]);
	        				httpClient = new HttpClient();
	                        httpClient.getHttpConnectionManager().getParams().setSoTimeout(1800000);
	                        //连接请求
	                        int app = httpClient.executeMethod(getMethod);
	        			} catch (Exception e) {
	        				e.printStackTrace();
	        			}
	                    } catch (Exception e) {  
	                    e.printStackTrace();  
	                }  
	            }  
	        }, 0,TimeUnit.SECONDS); 
		}
	}
	/**	
	 * @param args
	 */
	public static void main(String[] args)throws Exception{
		// TODO Auto-generated method stub
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "config/application-dataaccess.xml",
						"com/ctvit/sms/platform/sms-platform-service.xml" });
		MsgService msgService=context.getBean(MsgService.class);
//		msgService.doExecSendMsg();
	}
	public SynchronizeDataService getSynService() {
		return synService;
	}
	public void setSynService(SynchronizeDataService synService) {
		this.synService = synService;
	}

}
